<template>
  <div class="dt-shop-list-item">
    <ul
      v-infinite-scroll="getData"
      infinite-scroll-disabled="loading"
      infinite-scroll-distance="10"
    >
     <router-link tag="li"
      v-for="list in lists"
      :key="list.id"
      :to="`/detail?id=${list.id}`"
     >
       <img :src="list.image" alt="">
       <p class="shop-list-item-title">{{list.title}}</p>
       <p class="shop-list-item-price">{{list.price}}</p>
     </router-link>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'shoplist',
  data () {
    return {
      lists: [],
      loading: false,
      nextIndex: 0
    }
  },
  beforeRouteUpdate (to, from, next) {
    next()
    // 由于infinite scroll 组件会调用getData所以这里不比再调用了
    if (this.nextIndex === 20) {
      this.lists = []
      this.nextIndex = 0
      this.getData()
    } else {
      this.lists = []
      this.nextIndex = 0
    }
    // sessionStorage.setItem('shopid', this.$route.params.shopid)
    // this.getData()
  },
  beforeRouteLeave (to, from, next) {
    // console.log('leave', this.$route.params)
    sessionStorage.setItem('shopid', this.$route.params.shopid)
    next()
    // if (this.list === []) {
    //   this.getData()
    // }
  },
  methods: {
    getData () {
      // console.log('发送请求')
      const { shopid } = this.$route.params
      this.$http.getDataById(shopid, this.nextIndex)
        .then(resp => {
          // console.log(resp)
          this.lists = this.lists.concat(resp.items.list)
          this.nextIndex = resp.items.nextIndex
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.dt-shop-list-item {
  overflow: hidden;
  padding-top: 10px;
  ul {
    display: flex;
    justify-content: space-evenly;
    flex-wrap: wrap;
    li {
      width: 45%;
      img {
        width: 100%;
      }
    }
  }
}
</style>
